'use strict';
import React from 'react';
import * as ToastAndroid from "react-native/Libraries/Components/ToastAndroid/ToastAndroid.android";
import HttpHelper from "./HttpHelper";
import * as BizConstant from "../../gaqu/constant/BizContant";
import L from "../util/L";
import Exception from "handlebars/lib/handlebars/exception";

/** 短信有效时长重发时间间隔 */
const SMS_VALIDATE_TIME: number = 60;

/** 短信验证码帮助类 */
export default class SmsHelper {

    /**
     * 1.正在获取
     * 2.获取成功(倒计时)
     * 3.获取失败(获取)
     */

    _mCallBack: Function;
    _timeLeft: number = SMS_VALIDATE_TIME;

    // SmsHelper(callback: Function) {
    //     this._mCallBack = callback;
    // }

    constructor() {}

    /**
     * 单例
     */
    static getInstance() {
        if (typeof SmsHelper.instance === 'undefined') {
            SmsHelper.instance = new SmsHelper();
        }
        return SmsHelper.instance;
    }

    /**
     * 开始
     */
    start(callback: Function, tel: string): void {
        if (this._timeLeft < SMS_VALIDATE_TIME) return;
        this._mCallBack = callback;
        // let promise = new Promise((resolve, reject) =>{ });

        tel = tel.replace(/ /g, "");

        let map = new Map();
        map.set("mobile", tel);

        Promise.resolve()
            .then(() => {
                this._setText('正在获取')
            })
            .then(() => {
                this._doSendSms(map)  // 这里最好要传入参数
            })
            .then((res) => {
                // ToastAndroid.show('获取成功, 请注意查收' + res, ToastAndroid.SHORT);
                // this._setText('获取成功');
                // this._startClock();
            })
            .catch((e) => {
                ToastAndroid.show('获取失败' + e, ToastAndroid.SHORT);
                this._reset();
            });
    }

    /**
     * 获取验证码
     * @param map 网络请求附带的一些必要参数(比如:手机号码, 验证码类型)
     */
    _doSendSms(map: Map): void {
        if (!map) return;
        fetch(HttpHelper.getGetUrlWithParams(BizConstant.GET_CONFIRM_CODE, map), {
            method: "GET",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
        })
            .then((response) => {
                return response.text();     //将返回结果转换成文本
            })
            .then((res) => {
                L.logOnly('[验证码]返回：' + res);

                let resObj = JSON.parse(res);
                if(resObj.code === 0) {
                    this._setText('获取成功');
                    this._startClock();
                    return res;

                }
                ToastAndroid.show('获取失败' + resObj.msg, ToastAndroid.SHORT);
                this._setText('重新获取');
                throw new Exception(res.msg);
            })
            .catch((e) => {
                L.logOnly('[失败]获取验证码：' + e.toString());
            });
    }

    /** 回调提示信息 */
    _setText(info: string): void {
        if (!this._mCallBack) return;
        this._mCallBack(info);
    }

    /** 获取成功之后开始倒计时 */
    _startClock(): void {
        let timerInterval = setInterval(() => {
                this._setText((--this._timeLeft) + 's');
                if (this._timeLeft <= 0) {
                    timerInterval && clearInterval(timerInterval);
                    this._reset();
                }
            },
            1000,
        );
    }

    /** 初始化 */
    _reset() {
        this._timeLeft = SMS_VALIDATE_TIME;
        this._setText('获取');
    }
}
